package com.seckill.dao;

import com.seckill.vo.GoodsVo;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * @author yangjunwei
 * @date 2021/11/1 4:19 下午
 */
@Mapper
public interface GoodsDao {

    /**
     * 秒杀商品列表
     */
    @Select("select g.*,mg.miaosha_price,mg.stock_count,mg.start_date,mg.end_date " +
        "from miaosha_goods mg left join goods g " +
        "on g.id= mg.goods_id ")
    List<GoodsVo> listGoods();

    /**
     * 获取秒杀商品详情
     */
    @Select("select g.*,mg.miaosha_price,mg.stock_count,mg.start_date,mg.end_date " +
        "from miaosha_goods mg " +
        "left join goods g " +
        "on g.id= mg.goods_id " +
        "where mg.goods_id = #{goodsId} ")
    GoodsVo selectGoodsById(@Param("goodsId") long goodsId);

    /**
     * 秒杀商品-库存减1
     * 因为Mysql有行锁，where条件找到一行记录，单次update请求拥有对这个记录的排它锁。所以更新库存不会有并发问题。 同时加判断条件 stock_count >0 防止库存变为0，解决超卖问题。
     * @param goodsId 商品Id
     * @return int
     */
    @Update("update miaosha_goods set stock_count = stock_count-1  where id = #{goodsId} and stock_count >0 ")
    int decrStock(@Param("goodsId") long goodsId);

    /**
     * 商品库存+1
     * @param goodsId 商品Id
     * @return int
     */
    @Update("update miaosha_goods set stock_count = stock_count+1 where id = #{goodsId}")
    int incrStock(@Param("goodsId") long goodsId);


}
